package com.ecr.hub.service.mail.impl;

import java.net.ProxySelector;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import com.ecr.hub.service.mail.IHubMailSender;

@Component("hubMailSender")
public class HubMailSenderImpl implements IHubMailSender {

	@Autowired
	JavaMailSender mailSender;

	@Override
	public void sendMail(String to, String from, String subject, String body,
			String[] attachments) throws AddressException, MessagingException {

		// Define a new mail message
		MimeMessage message = mailSender.createMimeMessage();

		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);

		// Create a message part to represent the body text
		BodyPart messageBodyPart = new MimeBodyPart();
		messageBodyPart.setText(body);

		// use a MimeMultipart as we need to handle the file attachments
		Multipart multipart = new MimeMultipart();

		// add the message body to the mime message
		multipart.addBodyPart(messageBodyPart);

		// add any file attachments to the message
		addAttachments(attachments, multipart);

		// Put all message parts in the message
		message.setContent(multipart);
		
		// Désactivation des noms de domaine NetBIOS 
		ProxySelector.setDefault(null);

		// Send the message
		mailSender.send(message);

	}

	protected void addAttachments(String[] attachments, Multipart multipart)
			throws MessagingException, AddressException {

		for (int i = 0; i <= attachments.length - 1; i++) {
			String filename = attachments[i];
			MimeBodyPart attachmentBodyPart = new MimeBodyPart();

			// use a JAF FileDataSource as it does MIME type detection
			DataSource source = new FileDataSource(filename);
			attachmentBodyPart.setDataHandler(new DataHandler(source));

			attachmentBodyPart.setFileName(source.getName());

			attachmentBodyPart.setHeader("Content-Type",
					source.getContentType());
			attachmentBodyPart.setHeader("Content-ID", source.getName());
			attachmentBodyPart.setDisposition(Part.INLINE);

			// add the attachment
			multipart.addBodyPart(attachmentBodyPart);
		}
	}
}
